import { Layout, Menu } from 'antd';
import { useEffect, useState } from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom';
import { getCurrentModuleKey } from '../../utils/helpers';
import routes from '../../routes';

const { Footer, Content, Sider } = Layout;

const ModuleMenu = props => {
  const { moduleKey } = props;
  const matchChildrens = routes.find(
    route => route.key === moduleKey
  )?.children;
  const [selectedKey, setSelectedKey] = useState(
    matchChildrens ? matchChildrens[0].path : undefined
  );
  const navigate = useNavigate();
  //页面加载时既进入默认模块
  useEffect(() => {
    navigate(matchChildrens ? matchChildrens[0].path : undefined);
  }, []);
  const handleMenuClick = ({ key }) => {
    setSelectedKey(key);
  };

  const [collapsed, setCollapsed] = useState(false);

  return matchChildrens ? (
    <Layout
      style={{
        height: '100%',
      }}>
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={value => setCollapsed(value)}
        style={{ zIndex: 1 }}>
        <Menu
          theme='dark'
          selectedKeys={[selectedKey]}
          style={{ overflow: 'auto', height: '100vh', padding: 0, margin: 0 }}
          onClick={handleMenuClick}>
          {matchChildrens.map(route => (
            <Menu.Item
              style={{ width: '100%' }}
              key={route.path}
              onClick={() => {
                console.log(route.path);
                navigate(route.path);
              }}>
              {route.name}
            </Menu.Item>
          ))}
        </Menu>
      </Sider>
      <Layout className='site-layout'>
        <Content
          style={{
            marginLeft: collapsed ? 20 : 50,
            marginRight: 16,
            marginTop: 0,
          }}>
          <div
            style={{
              padding: 24,
              minHeight: 360,
            }}>
            <Routes>
              {matchChildrens.map(route => {
                return (
                  <Route
                    key={route.key}
                    path={route.path}
                    element={<route.component />}
                  />
                );
              })}
            </Routes>
          </div>
        </Content>
        <Footer
          style={{
            textAlign: 'center',
            marginTop: '24px',
            marginLeft: collapsed ? 20 : 50,
          }}>
          内测阶段，如有想法可联系小博（好想招个人帮我写前端）
        </Footer>
      </Layout>
    </Layout>
  ) : (
    <>{getCurrentModuleKey(routes)}模块，此页无内容</>
  );
};
export default ModuleMenu;
